<template>
  <div class="qrcode-container">
    <h2>签到二维码</h2>
    <div class="qrcode-image">
      <img v-if="qrCodeImage" :src="qrCodeImage" alt="签到二维码" />
      <div v-else class="loading">加载中...</div>
    </div>
    <div class="countdown">
      <p>二维码将在 {{ countdown }} 秒后刷新</p>
    </div>
  </div>


</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import axios from 'axios';
import {checkIn, getQc} from "@/api/qcqc.js";


const qrCodeImage = ref('');
const countdown = ref(0);
let countdownTimer = null;
let refreshTimer = null;

// 获取二维码
const fetchQrCode = async () => {
  try {
    const response = await getQc();
    console.log(response)
    qrCodeImage.value = `data:image/png;base64,${response.qrCode}`;
    console.log(qrCodeImage.value)
    countdown.value = response.expireIn;

    // 启动倒计时
    startCountdown();
  } catch (error) {
    console.error('获取二维码失败', error);
  }
};

// 倒计时
const startCountdown = () => {
  // 清除之前的倒计时
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }

  countdownTimer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(countdownTimer);
      fetchQrCode();
    }
  }, 1000);
};

onMounted(() => {
  // 首次获取二维码
  fetchQrCode();

  // 设置定时刷新
  refreshTimer = setInterval(fetchQrCode, 60000); // 1分钟刷新一次
});

onUnmounted(() => {
  // 清理定时器
  if (countdownTimer) clearInterval(countdownTimer);
  if (refreshTimer) clearInterval(refreshTimer);
});

</script>

<style scoped>
.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  max-width: 300px;
  margin: 0 auto;
}

.qrcode-image {
  width: 200px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 20px 0;
}

.qrcode-image img {
  width: 100%;
  height: 100%;
}

.loading {
  color: #999;
}

.countdown {
  font-size: 14px;
  color: #666;
}
</style>